package com.fxwater.api.common;

import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.fxwater.common.exception.BusinessException;

/**
 * @ClassName: Preconditions.java
 * @Description: 输入校验工具类
 *
 * @author: tzh
 * @date: 2018年6月2日 下午11:51:22
 *
 */
public final class Preconditions {
    private Preconditions() {}

    public static void checkArgument(boolean expression, String errorMessage) {
        if (!expression) {
            throw new BusinessException(errorMessage);
        }
    }

    public static <T> T checkNotEmpty(T reference, String errorMessage) {
        if (reference == null) {
            throw new BusinessException(errorMessage);
        }
        if ((reference instanceof String) && StringUtils.isEmpty((String) reference)) {
            throw new BusinessException(errorMessage);
        }
        return reference;
    }
    
    public static <T> T checkNotNull(T reference, String errorMessage) {
        if (reference == null) {
            throw new BusinessException(errorMessage);
        }
        return reference;
    }
    
    //^(13[0-9]|15[0-9]|18[0-9])\\d{8}$
    private static final Pattern PHONE_PATTERN = Pattern.compile("0?(13|14|15|17|18)[0-9]{9}");
    public static void checkPhoneNotValid(String phone){
        if( !PHONE_PATTERN.matcher(phone).matches() ){
            throw new BusinessException("手机号码格式不正确！");
        }
    }
    
    private static final Pattern CMS_PASSWORD_PATTERN = Pattern.compile("^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\\.#%'\\+\\*\\-:;^_`]+$)[,\\.#%'\\+\\*\\-:;^_`0-9A-Za-z]{8,20}$");
    /**
     * @Function: checkCmsPasswordNotValid
     * @Description: 验证CMS系统登录密码是否合法
     *
     * @param: @param password
     * @return: void
     * @throws
     */
    public static void checkCmsPasswordNotValid(String password){
        if( !CMS_PASSWORD_PATTERN.matcher(password).matches() ){
            throw new BusinessException("密码为8~20位数字、英文、符号至少两种组合的字符");
        }
    }
}
